import { GenericEnvStore } from "@/modules/dev-env/store/generic-env-store.ts";
import type { LocalVersionItem, ToolInstallVersionItem } from "@/modules/dev-env/common/types.ts";
import path from "@/framework/util/path.ts";
import type { BaseEnvMirror } from "@/modules/dev-env/mirror/mirror.ts";
import { MvndMirror } from "@/modules/dev-env/java/maven/mvnd-mirror.ts";
import type { EnvVariableConfig } from "@/modules/dev-env/store/types.ts";
import type { UnzipCompleteArgs } from "@common/archives-file-types.ts";
import { EnvTree } from "@/modules/dev-env/common/tree.ts";

/**
 * Maven Daemon环境管理
 */
export class MvndEnvStore extends GenericEnvStore<MvndEnvStore> {
  constructor() {
    super("maven-mvnd");
    this.icon = "icon-maven1";
  }

  protected async getVersionInfo(versionDir: string): Promise<LocalVersionItem | undefined> {
    const name = path.basename(versionDir);
    if (name.startsWith("maven-mvnd-")) {
      const binFile = path.join(versionDir, __WINDOWS__ ? "bin/mvnd.exe" : "bin/mvnd");
      if (await native.fs.exists(binFile)) {
        const [, , ...omit] = name.split("-");
        return {
          version: omit.join("-"),
          installPath: versionDir,
        };
      }
    }
  }

  getMirrors0(): BaseEnvMirror[] {
    return [
      new MvndMirror("aliyun"),
      new MvndMirror("tencent"),
      new MvndMirror("huaweicloud"),
      new MvndMirror("tsinghua"),
      new MvndMirror("nanjingu"),
      new MvndMirror("apache"),
    ];
  }

  getEnvVariables0(): EnvVariableConfig[] {
    return [
      {
        name: "PATH",
        getValue: () => path.join(this.installDir, EnvTree.currentVersionDir, "bin"),
        settable: false,
        readonly: true,
        copyName: false,
      },
    ];
  }

  async afterUnzipComplete(e: UnzipCompleteArgs, version: ToolInstallVersionItem) {
    // 重命名解压目录
    const versionDirName = path.basename(e.sourceFile, path.extname(e.sourceFile));
    const unzipedVersionDir = path.join(e.fileDir, versionDirName);
    const installDir = path.join(e.fileDir, `maven-mvnd-${version.version}`);
    await native.fs.rename(unzipedVersionDir, installDir);
  }
}
